import { readFileSync } from 'fs';
import { transform } from 'esbuild';

export const svgToJSX = (svg) =>
  `import React from "react";const ReactComponent = (props) => (${svg
    .replace(/\s([a-z-:]*)="[^"]*"/gu, (string, key) => {
      if (key.startsWith('data-')) return string;
      const keyWithoutDashes = camelCaseOn(key, '-');
      let keyWithoutDots = camelCaseOn(keyWithoutDashes, ':');
      if (keyWithoutDots === 'class') keyWithoutDots = 'className';
      if(keyWithoutDots === 'pId') keyWithoutDots = 'pid'
      return string.replace(key, keyWithoutDots);
    })
    .replace('>', ' {...props}>')});export default ReactComponent`;

const camelCaseOn = (string, delimiter) =>
  string
    .split(delimiter)
    .map((v, i) => (i === 0 ? v : v[0].toUpperCase() + v.slice(1)))
    .join('');

export default function svgPlugin() {
  return {
    name: 'svg',
    enforce: 'pre',
    async load(id) {
      //1.  id是文件路径， 判断是否是.svg文件
      if (id.endsWith('.svg')) {
        //2.  先把svg文件的字符转化为jsx语法的字符，然后用transform去编译
        const { code, warnings } = await transform(
          svgToJSX(readFileSync(id, 'utf-8')),
          { loader: 'jsx' }
        );
        for (const warning of warnings) {
          console.log(warning.location, warning.text);
        }
        // 3.  直接返回结果给vite处理
        return code;
      }
      if (id.endsWith('.svg?inline')) {
        const base64 = Buffer.from(
          readFileSync(id.replace('?inline', ''), 'utf-8')
        ).toString('base64');
        return `export default "data:image/svg+xml;base64,${base64}"`;
      }
    },
  };
}
